package com.springcloud.controller;

import com.springcloud.common.Friend;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author: 顾志杰
 */
@RestController
@Slf4j
public class ConsumerController {


    /**
     * 客户端负载均衡器
     * 简易版本
     */
    @Autowired
    private LoadBalancerClient client;

    @Autowired
    private RestTemplate restTemplate;



    @GetMapping("/hello")
    public String helloGet(){
        ServiceInstance instance = client.choose("eureka-client");
        if(instance == null){
            return "No avalilable instance";
        }
        String target = String.format("http://%s:%s/sayHi"
                ,instance.getHost()
                ,instance.getPort());
        log.info("url is {}",target);
        String forObject = restTemplate.getForObject(target, String.class);
        return forObject;
    }


    @PostMapping("/hello")
    public String helloPost(){
        ServiceInstance instance = client.choose("eureka-client");
        if(instance == null){
            return "No avalilable instance";
        }
        String target = String.format("http://%s:%s/sayHi"
                ,instance.getHost()
                ,instance.getPort());
        log.info("url is {}",target);
        Friend friend = Friend.builder().name("Eureka Consumer").build();
        friend.setName("Eureka Consumer");

        Friend friend1 = restTemplate.postForObject(target, friend, Friend.class);
        return friend1.toString();
    }
}
